package com.guobox.movies.usecase;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.guobox.movies.constant.Constant;
import com.guobox.movies.entity.MovieEntity;
import com.guobox.movies.entity.MovieType;
import com.guobox.movies.entity.NasProxy;
import com.guobox.movies.present.MovieListPresent;
import com.guobox.movies.proxy.HttpUrls;
import com.guobox.movies.utils.httpsutils.OkhttpsUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xuxinlei on 2017/6/30.
 */

public class MoviesModelImp implements MoviesModel {

    private static final String TAG = "MovieModelImp";
    private Handler handler = new Handler(Looper.getMainLooper());
    private MovieListPresent movieListPresent;
    private ExecutorService getMoviesThreadPool = Executors.newCachedThreadPool();

    public MoviesModelImp(MovieListPresent movieListPresent) {
        this.movieListPresent = movieListPresent;
    }

    @Override
    public void getMoviesFromNas(final String movieType, final String sort, final String ip) {

         Runnable getMoviesRunnable = new Runnable() {
            @Override
            public void run() {
                final Request request;
                Response response;
                HttpUrl.Builder builder = HttpUrls.getNasURL(ip);
                if (movieType.equals(MovieType.getMovieTypes().get(0).getTypeName())) {
                    builder.setEncodedQueryParameter(Constant.Category, "");
//
                } else {
                    builder.setEncodedQueryParameter(Constant.Category, movieType);
                }
                if (!sort.equals("name")) {
                    builder.setEncodedQueryParameter(Constant.Sort, sort);
                }
                request = new Request.Builder().url(builder.build()).build();
                OkhttpsUtils.getOkHttpClient().dispatcher().cancelAll();
                try {
                    response = OkhttpsUtils.getOkHttpClient()
                            .newCall(request)
                            .execute();
                    getMovies(response,movieType);
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            movieListPresent.moviesResultCallback(null, movieType);
                        }
                    });
                }
            }
        };

        getMoviesThreadPool.execute(getMoviesRunnable);

        //异步
//        Request request;
//        Log.i(TAG, HttpUrls.getNasURL().setEncodedQueryParameter(Constant.Category, "").build().toString());
//        if (movieType.equals(MovieType.getMovieTypes().get(0).getTypeName())) {
//            request = new Request.Builder().url(HttpUrls.getNasURL().setEncodedQueryParameter(Constant.Category, "").build()).build();
//        } else {
//            request = new Request.Builder().url(HttpUrls.getNasURL().setEncodedQueryParameter(Constant.Category, movieType).build()).build();
//        }
//        OkhttpsUtils.getOkHttpClient().dispatcher().cancelAll();
//        OkhttpsUtils.getOkHttpClient()
//                .newCall(request)
//                .enqueue(new Callback() {
//                    @Override
//                    public void onFailure(@NonNull Call call, @NonNull final IOException e) {
//                        handler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                movieListPresent.moviesResultCallback(null, movieType);
//                            }
//                        });
//                    }
//
//                    @Override
//                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                        String responseJson = response.body().string();
//                        JsonElement moviesJsonElement = Proxy_Nas.getContent(responseJson);
//                        List<MovieEntity> movieEntities = null;
//                        if (moviesJsonElement != null) {
//                            Gson gson = new Gson();
//                            List<MovieEntity> tempMovies = gson.fromJson(moviesJsonElement, new TypeToken<List<MovieEntity>>() {
//                            }.getType());
//                            movieEntities = new ArrayList<MovieEntity>();
//                            for (MovieEntity m :
//                                    tempMovies) {
//                                if (!m.isprivate()) {
//                                    movieEntities.add(m);
//                                }
//
//                            }
//                        }
//
//                        if (movieEntities != null) {
//                            final List<MovieEntity> finalMovieItems = movieEntities;
//                            handler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    movieListPresent.moviesResultCallback(finalMovieItems, movieType);
//                                }
//                            });
//                        }
//
//
//                    }
//                });

    }

    private void getMovies(Response response, final String movieType) throws IOException {
        String responseJson = response.body().string();
        List<MovieEntity> movieEntities = new ArrayList<>();
        Gson gson = new Gson();
        NasProxy nasProxy = gson.fromJson(responseJson, NasProxy.class);
        List<MovieEntity> tempMovies = nasProxy.getData();
        for (MovieEntity m :
                tempMovies) {
            if (!m.isprivate()) {
                movieEntities.add(m);
            }

        }
        final List<MovieEntity> finalMovieEntities = movieEntities;
        handler.post(new Runnable() {
            @Override
            public void run() {
                movieListPresent.moviesResultCallback(finalMovieEntities, movieType);
            }
        });
    }
}
